<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-50 to-purple-50 py-8">
    <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
      <div class="text-center mb-8">
        <h1 class="text-3xl font-bold text-gray-900 mb-2">天气查询</h1>
        <p class="text-gray-600">选择省份和城市，查询实时天气及未来预报（数据来源：itboy 天气接口）。</p>
      </div>

      <div class="bg-white rounded-lg shadow p-6 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 items-end">
          <div>
            <label class="text-sm text-gray-600">省 / 直辖市</label>
            <select v-model="selectedProvince" @change="onProvinceChange" class="mt-2 w-full border rounded px-3 py-2">
              <option value="">请选择省/直辖市</option>
              <option v-for="p in provinces" :key="p.code" :value="p.code">{{ p.name }}</option>
            </select>
          </div>

          <div>
            <label class="text-sm text-gray-600">城市</label>
            <select v-model="selectedCity" class="mt-2 w-full border rounded px-3 py-2" :disabled="cities.length===0">
              <option value="">请选择城市</option>
              <option v-for="c in cities" :key="c.code" :value="c.code">{{ c.name }}</option>
            </select>
          </div>

          <div>
            <button class="primary-button w-full" :disabled="!selectedCity || loading" @click="fetchWeather">{{ loading ? '查询中...' : '查询天气' }}</button>
          </div>
        </div>
      </div>

      <div v-if="error" class="mb-4 text-red-600">{{ error }}</div>

      <div v-if="weather && weather.status===200" class="space-y-6">
        <div class="bg-white rounded-lg shadow p-6 flex items-center justify-between">
          <div>
            <div class="text-xl font-semibold">{{ weather.cityInfo.city }} · 实时</div>
            <div class="text-sm text-gray-500">更新时间：{{ weather.cityInfo.updateTime }} · 数据时间：{{ weather.time }}</div>
            <div class="mt-2 text-4xl font-bold">{{ weather.data.wendu }}℃</div>
            <div class="text-sm text-gray-600">湿度：{{ weather.data.shidu }} · 空气质量：{{ weather.data.quality }} · PM2.5: {{ weather.data.pm25 }}</div>
          </div>
          <div class="text-right">
            <div class="text-sm text-gray-600">感冒指数</div>
            <div class="mt-2 max-w-xs text-sm text-gray-700">{{ weather.data.ganmao }}</div>
          </div>
        </div>

        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          <div v-for="(f, idx) in weather.data.forecast.slice(0,9)" :key="idx" class="bg-white rounded-lg shadow p-4">
            <div class="flex items-center justify-between">
              <div>
                <div class="text-sm text-gray-600">{{ f.ymd }} · {{ f.week }}</div>
                <div class="text-lg font-semibold">{{ f.type }}</div>
              </div>
              <div class="text-right">
                <div class="text-sm text-gray-600">风向：{{ f.fx }} · {{ f.fl }}</div>
                <div class="text-sm text-gray-500">AQI: {{ f.aqi }}</div>
              </div>
            </div>
            <div class="mt-3 text-sm text-gray-700">{{ f.notice }}</div>
            <div class="mt-2 text-sm text-gray-600">{{ f.low }} / {{ f.high }}</div>
          </div>
        </div>
      </div>

      <div v-else-if="weather && weather.status!==200" class="bg-white rounded-lg shadow p-6 text-gray-700">未能获取天气：{{ weather && weather.message }}</div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useHead } from '#imports'

useHead({ title: '天气查询 - 八八在线工具' })

let provinces = []
try {
  const mod = await import('~/composables/cityCodes.js')
  provinces = mod.default || mod.provinces || []
} catch (e) {
  // 回退
  try {
    const mod2 = await import('~/composables/cityCodes.js')
    provinces = mod2.default || mod2.provinces || []
  } catch (e2) {
    provinces = []
    console.warn('未能加载城市编码数据：', e2)
  }
}

const selectedProvince = ref('')
const selectedCity = ref('')
const cities = ref([])
const loading = ref(false)
const error = ref('')
const weather = ref(null)

function onProvinceChange() {
  error.value = ''
  weather.value = null
  selectedCity.value = ''
  const p = provinces.find(p => p.code === selectedProvince.value || p.name === selectedProvince.value)
  // 如果 provinces 中没有 code 字段（脚本生成时只包含 name 和 cities），尝试按 name 匹配
  cities.value = p ? (p.cities || []) : []
}

async function fetchWeather() {
  error.value = ''
  weather.value = null
  if (!selectedCity.value) {
    error.value = '请先选择城市'
    return
  }
  loading.value = true
  try {
  // 使用同源的后端代理，避免浏览器被第三方接口的 CORS 限制阻止
  // 后端代理位于 /api/weather?city=xxx
  const res = await fetch(`/api/weather?city=${encodeURIComponent(selectedCity.value)}`)
    if (!res.ok) throw new Error(`HTTP ${res.status}`)
    const data = await res.json()
    weather.value = data
  } catch (e) {
    console.error(e)
    error.value = '获取天气时发生错误，请稍后重试'
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.primary-button{
  background: linear-gradient(90deg,#4f46e5,#06b6d4);
  color: white;
  padding: 0.5rem 0.75rem;
  border-radius: 0.375rem;
  font-weight: 600;
}
</style>
